<?php
namespace app\index\controller;

use app\common\model\Order;
use app\common\model\OrderLog;
use think\Controller;
use app\common\controller\IndexBase;
use think\Db;
use think\cache\driver\Redis;

class Index extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }
    /**
     * 弹窗处理
     * @return mixed
     */
    public function index()
    {
        $type = $this->request->param('type');
        $data = $this->request->param();
        $html = "";
        switch ($type) {
            case 'login':
                $html = $this->fetch('login/login');
                break;
            case 'register':
                $html = $this->fetch('login/register');
                break;
            case 'forget_pwd':
                $html = $this->fetch('login/forgot_pwd');
                break;
            case 'change_pwd':
                $html = $this->fetch('login/change_pwd');
                break;
            case 'player_center':
                $html = $this->fetch('login/player_center');
                break;
            case 'customer_service':
                $html = $this->fetch('login/customer_service');
                break;
            case 'user_auth':
                $html = $this->fetch('login/player_auth');
                break;
            case 'player_loginout':
                $html = $this->fetch('login/player_loginout');
                break;
            case 'submit_report':
                $data['title'] = self::getReportTitle($data['reportType']);
                $this->assign("data",$data);
                $html = $this->fetch('login/submit_report');
                break;
            case 'pay':
                $data['money'] = number_format(round($data['amount']/100, 2),2);
                $this->assign('data', $data);
                $is_weixin = is_weixin();
                $this->assign('is_weixin',$is_weixin);
                $html = $this->fetch('login/pay');
                break;
            case 'report_list':
                $data = DB::connect('db_config_aiqi')->name('customer_services')->where(['uid'=>$this->uid])->order("id desc")->select();
                $this->assign("data",$data);
                $html = $this->fetch('login/report_list');
                break;
            case 'report_detail':
                $data = DB::connect('db_config_aiqi')->name('customer_services')->find($data['id']);
                $data['content'] = json_decode($data['content'],true);
                $detail = DB::connect('db_config_aiqi')
                    ->name('customer_detail')
                    ->where(['customer_id'=>$data['id']])
//                    ->order('update_time desc')
                    ->select();
                $this->assign("data",$data);
                $this->assign("detail_list",$detail);
                $html = $this->fetch('login/report_detail');
                break;
            case 'article_list':
                $data = $this->request->param();
                $date = date("Y-m-d");
                $map=[];
                $map[]=['status','=',1];
                $map[] = ['gid', 'in', "0,".$data['gid']];
                $map[] = ['cid', 'in', "0,".$data['cid']];
                $map[]=['star_date', '<=', $date];
                $map[]=['end_date', '>=', $date];
                $list = DB::connect('db_config_aiqi')->name('article')->where($map)->order("sort desc")->select();
                $this->assign("list",$list);
                $html = $this->fetch('login/article_list');
                break;
            case 'article_detail':
                $data = $this->request->param();
                $article = DB::connect('db_config_aiqi')->name('article')->find($data['id']);
                $this->assign("article",$article);
                $html = $this->fetch('login/article_detail');
                break;
            case 'next_detail':
                $data = $this->request->param();
                $date = date("Y-m-d");
                $map=[];
                $map[]=['status','=',1];
                $map[] = ['gid', 'in', "0,".$data['gid']];
                $map[] = ['cid', 'in', "0,".$data['cid']];
                $map[]=['star_date', '<=', $date];
                $map[]=['end_date', '>=', $date];
                $order = "";
                if($data['next'] == 1){
                    $map[] = ['id', '>', $data['id']];
                }else{
                    $order = "id desc";
                    $map[] = ['id', '<', $data['id']];
                }
                $article = DB::connect('db_config_aiqi')->name('article')->where($map)->order($order)->find();

                if(empty($article)){
                    $this->error('没有更多了');
                }
                $this->assign("article",$article);
                $html = $this->fetch('login/article_detail');
                break;
            case 'shouye_fuli':
                $data = $this->request->param();
                $date = date("Y-m-d");
                $map=[];
                $map[]=['status','=',1];
                $map[] = ['gid', 'in', "0,".$data['gid']];
                $map[] = ['cid', 'in', "0,".$data['cid']];
                $map[]=['star_date', '<=', $date];
                $map[]=['end_date', '>=', $date];
                $map[] = ['shouye','=',1];
                $order = "sort desc";
                if(!empty($data['id']) && $data['id'] > 0){
                    if($data['next'] == 1){
                        $order="";
                        $map[] = ['id', '>', $data['id']];
                    }else{
                        $order = "id desc";
                        $map[] = ['id', '<', $data['id']];
                    }
                }

                $redis = new Redis();
                $redis->select(5);
                $shouye_id = $redis->get($data['uid']);

                if(!empty($shouye_id)){
                    $map[] = ['id','not in',$shouye_id];
                }else{
                    $shouye_id = [];
                }
                $article = DB::connect('db_config_aiqi')->name('article')->where($map)->order($order)->find();
                if(empty($article) && $data['id'] == 0){
                    $this->result('','0','没有更多了');
                }
                $shouye_id[] = $article['id'];
                $redis->set($data['uid'],$shouye_id,43200);//
                if(empty($article)){
                    $this->result('','0','没有更多了');
                }
                $this->assign("article",$article);
                $html = $this->fetch('login/shouye_fuli');
                break;
            case 'order':
                $order = $this->channelOrder($data);
                if($data['cid'] == '8'){
                    $this->YY_order();
                }
                $this->success("成功","",['order_no'=>$order['order_no']]);
                break;
            default:
                $this->error('参数错误');
        }
        return $html;
    }

    public function getWxConfig(){
        $request = $this->request->param();
        $redirect_uri = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/game/play/'.$request['gid'];
        $redirectUri = urlencode($_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/game/play/'.$request['gid']);
        if($request['cid'] > 0){
            $redirectUri = urlencode($_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/game/play/'.$request['gid'].'/'.$request['cid']);
        }
        $wx_data = get_wx_openid_url().'&redirect_uri='.$redirectUri.'#wechat_redirect';

        $this->success('获取成功','',$wx_data);
    }

    public function getWxLogin(){
        $wx_data = get_wx_openid_url();
        $this->success('获取成功','',$wx_data);
    }

    private static function getReportTitle($reportType){
        switch ($reportType){
            case 1;
                $title = "充值问题";
                break;
            case 2;
                $title = "账号问题";
                break;
            case 3;
                $title = "BUG问题";
                break;
            case 4;
                $title = "举报问题";
                break;
            case 5;
                $title = "意见反馈";
                break;
            default:
                $title = "充值问题";
                break;
        }
        return $title;
    }


    protected function channelOrder($data)
    {
        if(empty($data['sign'])){
            $this->error('sign不能为空');
        }
        if(empty($data['type'])){
            $this->error('请选择支付方式');
        }
        if(empty($data['amount']) || $data['amount'] <= 0){
            $this->error('支付金额错误');
        }
        if(empty($data['goods_name'])){
            $this->error('商品名称不能为空');
        }
        //校验提交的游戏id、uid、cid
        if(empty($data['gid']) || $data['gid'] != $this->gid){
            $this->error('游戏id错误');
        }
        $grr = [30];
        $uid = $this->uid;
        if(in_array($data['gid'], $grr)){
            $player_old = DB::connect('db_config_aiqi')->name('player_old')->where(['banma_id'=>$data['uid']])->find();
            if($player_old){
                $this->uid = $player_old['banma_id'];
            }
        }

        if(empty($data['uid']) || $data['uid'] != $this->uid){
            $this->error('用户id错误');
        }
        if(!empty($data['cid']) && $data['cid'] != $this->cid){
            $this->error('游戏渠道id错误');
        }

        $sid = $data['sid'] ?? 0;

        unset($data['type']);
        unset($data['cid']);
        unset($data['sid']);
        unset($data['token']);

        if(!$this->checkSign($data,2)){
            $this->error('签名错误');
        }

        $data['type'] = 3;
        $data['num'] = $data['num'] ?? 1;
        $data['sid'] = $sid;
        $data['uid'] = $uid;
        $data['gid'] = $this->gid;
        $data['cid'] = $this->cid;
        $data['is_test'] = 0;
        if($this->game['gstatus'] == 2 || in_array($this->gid,[10,11])){
            $data['is_test'] = 1;
        }
        try {
            //创建订单
            $order = $this->create_order($data);
            $order['user_id'] = $uid;
            return $order;
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
    }

    protected function create_order($data)
    {
        $data['order_no'] = get_order_sn($this->uid,$this->gid,$data['type']);
        $order = new Order();
        $orderId = $order->creatOrder($data);
        $order =  Order::find($orderId);
        OrderLog::addLog($order->order_no, $order->order_status, $order->type);
        return $order;
    }
}